package com.Servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.Servlet.Dao.usersEntity;
import com.User.Dao.Record;

/**
 * Servlet implementation class readerReturnBook
 */
@WebServlet("/readerReturnBook")
public class readerReturnBook extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public static int differentDaysByMillisecond(Date date1,Date date2){
        int days = (int) ((date2.getTime() - date1.getTime()) / (1000*3600*24));
        return days;
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String[] values = request.getParameterValues("checkBook");
		String userSno = request.getParameter("userSno");
		request.setAttribute("userSno", userSno);
		request.setAttribute("flag", "returnInfo");
		if(values != null) {
			for(int i = 0; i < values.length; i++) {
				try {
					Date timer = usersEntity.endTime(userSno, values[i]);
					if(timer != null) {
						Date date = new Date();
						SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
						String createDate = dateFormat.format(date);
						SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			            Date dates = format.parse(createDate);
			            Date beginTime = usersEntity.returmBeginTime(userSno, values[i]);
			            int preDiffMoney = differentDaysByMillisecond(dates, timer);
			            int fine = 0;
			            usersEntity.refolk(-1, userSno);
						if(dates.getTime() > timer.getTime()) {
							fine = -preDiffMoney;
							usersEntity.fine(preDiffMoney, userSno);
						}
						Record re = new Record(values[i], userSno, dateFormat.format(beginTime), dateFormat.format(dates), fine + "");
						usersEntity.insertRecord(re);
					}
					usersEntity.updateReturnBookToReader(userSno, values[i]);
				} catch (ClassNotFoundException | SQLException | ParseException e) {
					System.out.println("The " + i + " return book failed");
				}
			}
		}
		request.getRequestDispatcher("Main.jsp").forward(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
